package com.szy.bigevent.controller;

import com.szy.bigevent.annotions.Log;
import com.szy.bigevent.dto.AvatarDTO;
import com.szy.bigevent.enums.BusinessType;
import com.szy.bigevent.pojo.Result;
import com.szy.bigevent.pojo.User;
import com.szy.bigevent.service.UserService;
import com.szy.bigevent.utils.JwtUtil;
import com.szy.bigevent.utils.Md5Util;
import com.szy.bigevent.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.List;
import java.util.Map;

import static com.szy.bigevent.interceptor.LoginInterceptor.AUTHORIZATION_HEADER;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

//    @Log(operation = "user register",businessType = BusinessType.REGISTER)
    @PostMapping("/register")
    public Result<User> register(final String username, final String password) {
        final User existingUser = userService.findByUsername(username);
        if (existingUser == null) {
            userService.register(username, password);
            return Result.success(null,"注册成功");
        } else {
            return Result.error("用户名已被占用");
        }
    }

//    @Log(operation = "user login", businessType = BusinessType.LOGIN)
    @PostMapping("/login")
    public Result<String> login(final String username, final String password) {
        final User existingUser = userService.findByUsername(username);
        if (existingUser == null) {
            return Result.error("用户不存在");
        }
        if (Md5Util.getMD5String(password).equals(existingUser.getPassword())) {
            final Map<String, Object> map = Map.of("id", existingUser.getId(),
                    "username", existingUser.getUsername());
            final String token = JwtUtil.genToken(map);
            // Save token to redis
            final ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            // If key is token, and when we validate, and the token doesn't exist, then it has expired.
            operations.set(token, token, Duration.ofHours(1));
            // Return JWT token
            return Result.success(token);
        } else {
            return Result.error("密码错误");
        }
    }

    @GetMapping("/info")
    public Result<User> getUserInfo(){
        User user = userService.getUserInfo();
        return Result.success(user);
    }

    @PostMapping("/logout")
    public Result logout(@RequestHeader(AUTHORIZATION_HEADER) String token){
        final ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        //缓存中的token:本地安装redis版本过低，不支持该方法
//        operations.getAndDelete(token);
        try {
            //由于本地安装本版问题，仅作假性删除
            operations.set(token, "", Duration.ofSeconds(10));
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("退出登录，发生异常");
        }

        return Result.success(null,"退出登录成功");
    }

    //用于文章管理查询：获取所有用户信息{id,username}
    @GetMapping("/findUsers")
    public Result<List<User>> findUsersForSearch(){
        List<User> users = userService.getAllUsers();
        return Result.success(users);
    }

    @PutMapping("/update")
    public Result<String> update(@RequestBody final User user) {
        userService.update(user);
        return Result.success("修改成功");
    }

    @PutMapping("/updateAvatar")
    public Result<String> updateAvatar(@RequestBody final AvatarDTO avatarDTO) {
        userService.updateAvatar(avatarDTO.getAvatarUrl());
        return Result.success("头像修改成功");
    }

    @PatchMapping("/updatePwd")
    public Result<String> updatePwd(@RequestBody Map<String, String> params, @RequestHeader(AUTHORIZATION_HEADER) final String token) {
        final String oldPwd = params.get("old_pwd");
        final String newPwd = params.get("new_pwd");
        final String rePwd = params.get("re_pwd");
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要的参数");
        }

        final Map<String, Object> map = ThreadLocalUtil.get();
        final String username = (String) map.get("username");
        if (!rePwd.equals(newPwd)) {
            return Result.error("两次结果不一样");
        }
        final User user = userService.findByUsername(username);
        if (!user.getPassword().equals(Md5Util.getMD5String(oldPwd))) {
            return Result.error("密码填写不正确");
        }

        userService.updatePwd(newPwd);
        // Delete token in redis.
        final ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
//        operations.getOperations().delete(token);
        //由于本地安装本版问题，仅作假性删除
        operations.set(token, "", Duration.ofSeconds(10));
        return Result.success("密码修改成功");
    }

}
